package com.tjsinfo.tjsoa.system.action;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.util.MessageResources;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;

import com.tjsinfo.tjsoa.Dao.IQbcDao;
import com.tjsinfo.tjsoa.common.PaginationSupport;
import com.tjsinfo.tjsoa.system.bo.IDepartmentBo;
import com.tjsinfo.tjsoa.system.vo.TSystemDepartment;
import com.tjsinfo.tjsoa.system.vo.TSystemUserDepartment;

public class DepartmentManageAction extends DispatchAction {
	private IDepartmentBo departmentBo;
	
	public IDepartmentBo getDepartmentBo() {
		return departmentBo;
	}

	public void setDepartmentBo(IDepartmentBo departmentBo) {
		this.departmentBo = departmentBo;
	}
	private IQbcDao qbcDao;

	public void setQbcDao(IQbcDao qbcDao) {
		this.qbcDao = qbcDao;
	}
	//部门列表
	public ActionForward departmentList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			List<TSystemDepartment> departmentlist = new ArrayList<TSystemDepartment>();
			Integer level= Integer.valueOf(request.getParameter("level"));
			DetachedCriteria criteria = DetachedCriteria.forClass(TSystemDepartment.class);
			if(level==0){
				SimpleExpression depart = Restrictions.eq("levelNo", level+1);
				criteria.add(depart);
			}else{
				String id=request.getParameter("id");
				SimpleExpression depart = Restrictions.like("id", id+"%");
				SimpleExpression departs = Restrictions.eq("levelNo", level+1);
				criteria.add(depart);
				criteria.add(departs);
			}
			List<Order> orderList=new ArrayList<Order>();
			orderList.add(Order.asc("orderNo"));
			orderList.add(Order.asc("id"));
			
			Locale locale=getLocale(request);
			MessageResources message=getResources(request);
			Integer pageSize=Integer.valueOf(message.getMessage(locale, "departmentList.size"));
			String pageStr=request.getParameter("pageNo");
			if(pageStr==null)pageStr="0";
			int page=Integer.valueOf(pageStr).intValue();
			int startIndex=pageSize*page;
			PaginationSupport paginationSupport=qbcDao.findPageByCriteria(criteria,orderList, pageSize.intValue(),startIndex);
			request.setAttribute("paginationSupport", paginationSupport);
			for (Iterator iterator = paginationSupport.getItems().iterator(); iterator.hasNext();) {
				TSystemDepartment systemDepartment = (TSystemDepartment) iterator.next();
				DetachedCriteria detachedCriteria	 = DetachedCriteria.forClass(TSystemUserDepartment.class);
				detachedCriteria.add(Restrictions.eq("departmentId", systemDepartment.getId()));
				if (qbcDao.getCriteria(detachedCriteria).size() > 0) {
					systemDepartment.setRemarks("1");
				}
				else
				{
					systemDepartment.setRemarks("0");
				}
				departmentlist.add(systemDepartment);
				
			}
			request.setAttribute("paginationSupport", paginationSupport);
			request.setAttribute("departmentlist", departmentlist);
			if(request.getAttribute("alert")!=null)request.setAttribute("alert", request.getAttribute("alert"));
			return mapping.findForward("departmentList");
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("Exception", e);
			return mapping.findForward("failed");
		}
	}
	//添加部门
	public ActionForward departmentSave(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			Integer level= Integer.valueOf(request.getParameter("level"));
			String alert="";
			TSystemDepartment d=new TSystemDepartment();
			d.setDeptName(request.getParameter("departName"));
			d.setLevelNo(level+1);
			d.setIsDel(Integer.valueOf(1));
			d.setRemarks("0");
			d.setOrderNo(Integer.valueOf(request.getParameter("orderNo")));
			if(level.intValue()==0){//处理一级栏目
				DetachedCriteria criteria = DetachedCriteria.forClass(TSystemDepartment.class);
				SimpleExpression departs = Restrictions.eq("levelNo", level+1);
				criteria.add(departs);
				criteria.addOrder(Order.asc("id"));
				List<TSystemDepartment> departmentList=qbcDao.getCriteria(criteria);
				if(departmentList.size()<89){
					Integer tempId=10;
					d.setLevelNo(level+1);
					boolean isSave=false;//保存状态
					for (TSystemDepartment department:departmentList) {
						Integer id=Integer.valueOf(department.getId().trim());
						if(!id.equals(tempId)){//存在ID中断的情况
							String str=tempId.toString();
							d.setId(str);
							alert=departmentBo.save(d);
							isSave=true;
							break;
						}
						++tempId;
					}
					//新增ID
					String str=String.valueOf(tempId.intValue());
					d.setId(str);
					if(!isSave)alert=departmentBo.save(d);
				}else{
					alert="对不起,当前数量已经超出最大长度,请与开发人员联系!";
				}
			}else{
				DetachedCriteria criteria = DetachedCriteria.forClass(TSystemDepartment.class);
				String parentId=request.getParameter("id");
				SimpleExpression depart = Restrictions.like("id", parentId+"%");
				SimpleExpression departs = Restrictions.eq("levelNo", level+1);
				criteria.add(depart);
				criteria.add(departs);
				List<Order> orderList=new ArrayList<Order>();
				orderList.add(Order.asc("orderNo"));
				List<TSystemDepartment> departmentList=qbcDao.getCriteria(criteria);
				if(departmentList.size()<99){
					String tempId="00";
					d.setLevelNo(level+1);
					boolean isSave=false;//保存状态
					for (TSystemDepartment department:departmentList) {
						String id=department.getId().trim();
						if(!id.toString().equals(parentId+tempId)){//存在ID中断的情况
							d.setId(parentId+tempId);
							alert=departmentBo.save(d);
							isSave=true;
							break;
						}
						int a=Integer.valueOf(tempId).intValue()+1;
						tempId=String.valueOf(a);
						if(tempId.length()==1)tempId="0"+tempId;
					}
					//新增ID
					d.setId(parentId+tempId);
					if(!isSave)alert=departmentBo.save(d);
					
				}else{
					alert="对不起,当前数量已经超出最大长度,请与开发人员联系!";
				}
			}
			
			
			
			//生成全部部门树
			Locale locale=getLocale(request);
			MessageResources message=getResources(request);
			String nodeName=message.getMessage(locale, "allDepartmentNode.Name");
			String url=request.getSession().getServletContext().getRealPath("/")+"js/xyTree/js/";
			departmentBo.createAllOrganizeClickJS(url, nodeName);
			
			departmentBo.createOrganizeClickJS(url, nodeName);
						
			if(!alert.equals(""))request.setAttribute("alert", alert);
			return mapping.findForward("departmentManageList");
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("Exception", e);
			return mapping.findForward("failed");
		}
	}
	//修改部门
	public ActionForward departmentUpdate(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			
			return mapping.findForward(null);
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("Exception", e);
			return mapping.findForward("failed");
		}
	}
	//删除部门
	public ActionForward departmentDel(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			String alert="";
			DetachedCriteria checkDC = DetachedCriteria.forClass(TSystemDepartment.class);
			String parentId=request.getParameter("did");
			SimpleExpression departId = Restrictions.like("id", parentId+"%");
			SimpleExpression departsLevel = Restrictions.eq("isDel", 1);
			checkDC.add(departId);
			checkDC.add(departsLevel);
			List<TSystemDepartment> checkDepartmentList=qbcDao.getCriteria(checkDC);
			if(checkDepartmentList.size()>1){
				
				alert="当前部门还有下一级部门,请删除或禁用下级部门后继续操作!";
				
			}else{

				TSystemDepartment de=departmentBo.findById(parentId);
				DetachedCriteria detachedCriteria	 = DetachedCriteria.forClass(TSystemUserDepartment.class);
				detachedCriteria.add(Restrictions.eq("departmentId", de.getId()));
				if (qbcDao.getCriteria(detachedCriteria).size() > 0) {
					de.setRemarks("1");
				}
				else
				{
					de.setRemarks("0");
				}

				if(Integer.valueOf(de.getRemarks())>0){
					if(de.getIsDel()==1){
						de.setIsDel(Integer.valueOf(0));
					}else{
						de.setIsDel(Integer.valueOf(1));
					}
					departmentBo.update(de);
				}else{
					departmentBo.delete(de);
				}
				//生成全部部门树
				Locale locale=getLocale(request);
				MessageResources message=getResources(request);
				String nodeName=message.getMessage(locale, "allDepartmentNode.Name");
				String url=request.getSession().getServletContext().getRealPath("/")+"js/xyTree/js/";
				departmentBo.createAllOrganizeClickJS(url, nodeName);
				
				departmentBo.createOrganizeClickJS(url, nodeName);
				
			}
			if(!alert.equals(""))request.setAttribute("alert", alert);
			return mapping.findForward("departmentManageList");
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("Exception", e);
			return mapping.findForward("failed");
		}
	}
	//修改部门排列序号
	public ActionForward departmentUpdateOrder(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			String id=request.getParameter("myid");
			TSystemDepartment de=departmentBo.findById(id);
			de.setOrderNo(Integer.valueOf(request.getParameter("updateOrderNo")));
			departmentBo.update(de);
			//生成全部部门树
			Locale locale=getLocale(request);
			MessageResources message=getResources(request);
			String nodeName=message.getMessage(locale, "allDepartmentNode.Name");
			String url=request.getSession().getServletContext().getRealPath("/")+"js/xyTree/js/";
			departmentBo.createAllOrganizeClickJS(url, nodeName);
			
			departmentBo.createOrganizeClickJS(url, nodeName);
			
			return mapping.findForward("departmentManageList");
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("Exception", e);
			return mapping.findForward("failed");
		}
	}

}
